package com.lhoverc.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author: LiCheng
 * @CreateTime: 2025-04-14
 * @Description:
 * @Version: 1.0
 */
@Data
@Slf4j
@Component
public class AliOSSUtil {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    //保存OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET
    private EnvironmentVariableCredentialsProvider credentialsProvider;
    // 填写Bucket名称
    private String bucketName = "community-visitor-system";

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    public String upload(MultipartFile file) throws Exception {

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        //获取上传的文件输入流
        InputStream inputStream = file.getInputStream();

        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = "http://" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        //关闭ossClient
        ossClient.shutdown();
        return url;
    }
}
